<template>
  <div class="app-container">
    
<br>
<br>
    <el-button type="primary" @click="add">添加职务</el-button>
    <br>
    <br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    > 
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="所属部门" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deptName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职务名称" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="是否管理岗" width="150" align="center">
        <template slot-scope="scope">
          {{ (scope.row.isManager === 1 || scope.row.isManager === '1')  ? '是': '否'}}
        </template>
      </el-table-column>
      <el-table-column label="可见会员敏感信息" width="200" align="center">
        <template slot-scope="scope">
          {{ (scope.row.isDesensitization === 1 || scope.row.isDesensitization === '1')  ? '是': '否'}}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" align="center" width="300" >
        <template slot-scope="scope">
          <el-button type="primary"  @click="getInfo(scope.row)" size="small">详情</el-button>
          <el-button type="success"  @click="update(scope.row)" size="small">修改</el-button>
          <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="->, total, prev, pager, next"
      :total="this.total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="clickCurPage"
      >
    </el-pagination>
  <el-dialog title="职务详情" :visible.sync="infoVisible">
      <h2>职务信息</h2>
      <el-form ref="info" :model="info" label-width="120px">
        <el-form-item label="所属部门">
          <el-select v-model="info.deptId" :disabled="true" placeholder="请选择">
            <el-option
              v-for="item in depts"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职务名称">
            <el-input v-model="info.name" :disabled="true" />
        </el-form-item>
        <el-form-item label="是否管理岗">
          <el-radio v-model="info.isManager" label="1" :disabled="true" >是</el-radio>
          <el-radio v-model="info.isManager" label="0" :disabled="true" >否</el-radio>
        </el-form-item>
        <el-form-item label="隐藏会员敏感信息">
          <el-radio v-model="info.isDesensitization" label="1" :disabled="true" >是</el-radio>
          <el-radio v-model="info.isDesensitization" label="0" :disabled="true" >否</el-radio>
        </el-form-item>
      </el-form>
      <h2>权限信息</h2>
      <el-row>
        <el-col :span=24 :offset=2>
          <div style="background-color: white;width:80%;border: 2px solid #E4E7ED;padding: 10px;">
            <el-tree
              ref="menusInfo"
              :data="menusEnumInfo"
              show-checkbox
              node-key="id"
              :default-expand-all="true"
              :props="{children: 'children', label: 'name'}">
            </el-tree>
          </div>
        </el-col>
      </el-row>
  </el-dialog>
  <el-dialog :title="dialogTitle" :visible.sync="formVisible" :closeOnClickModal="false">
      <h2>职务信息</h2>
      <el-form ref="form" :model="form" label-width="120px" :rules="formRules">
        <el-form-item label="所属部门" prop="deptId" label-width="160px">
          <el-select v-model="form.deptId" placeholder="请选择">
            <el-option
              v-for="item in depts"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职务名称" prop="name" label-width="160px">
            <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="是否管理岗" label-width="160px">
          <el-radio v-model="form.isManager" label="1">是</el-radio>
          <el-radio v-model="form.isManager" label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="隐藏会员敏感信息" label-width="160px">
          <el-radio v-model="form.isDesensitization" label="1">是</el-radio>
          <el-radio v-model="form.isDesensitization" label="0">否</el-radio>
        </el-form-item>
      </el-form>
      <h2>权限信息</h2>
      <el-row>
        <el-col :span=24 :offset=2>
          <div style="background-color: white;width:80%;border: 2px solid #E4E7ED;padding: 10px;">
            <el-tree
              ref="menusForm"
              :data="menusEnum"
              show-checkbox
              node-key="id"
              :default-expand-all="true"
              :props="{children: 'children', label: 'name'}">
            </el-tree>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm" :loading="commitLoading">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      
  </el-dialog>
  </div>
</template>

<script>

import { getList, edit, add, del} from '@/api/jobDuty'
import { getList as deptList } from '@/api/dept'
import { getListByJobDutyId, getTreeList as getMenuTreeList } from '@/api/menu'


export default {
  filters: {

  },
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) callback(new Error('请输入名称')) 
      else callback()
    }
    const validateDept = (rule, value, callback) => {
      if (!value) callback(new Error('请选择部门')) 
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      info: {},
      form: {},
      dialogTitle: '添加职务',
      depts:[],
      menusEnum: [],
      menusEnumInfo: [],
      formRules: {
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        deptId: [{ required: true, trigger: 'blur', validator: validateDept }],
      },
      commitLoading: false,
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getList({currentPage: this.currentPage, pageSize: this.pageSize}).then(res=>{
        console.log(res)
        this.list = res.data
        this.listLoading = false
        deptList({currentPage: 1, pageSize: 100}).then(deptRes=>{
          this.depts = deptRes.data
        })
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    getInfo(row) {
      this.info = row
      this.$set(this.info, 'isManager', this.info.isManager+'')
      this.$set(this.info, 'isDesensitization', this.info.isDesensitization+'')
      getMenuTreeList().then(menusRes => {
        this.menusEnumInfo = this.setDesiable(JSON.parse(JSON.stringify(menusRes.data)))
        getListByJobDutyId(row.id).then(menuListRes=>{
          console.log("menuListRes:", menuListRes)
          this.$refs.menusInfo.setCheckedKeys(menuListRes.data)
        })
      })
      this.infoVisible = true
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改职务'
      this.form = JSON.parse(JSON.stringify(row))
      this.$set(this.form, 'isManager', this.form.isManager+'')
      this.$set(this.form, 'isDesensitization', this.form.isDesensitization+'')
      getMenuTreeList().then(menusRes => {
        this.menusEnum = menusRes.data
        getListByJobDutyId(this.form.id).then(menuListRes=>{
          console.log("menuListRes:", menuListRes.data)
          this.$refs.menusForm.setCheckedKeys(menuListRes.data.filter(id=> !this.menusEnum.map(menu => menu.id).includes(id)))
        })
      })
      this.formVisible = true
    },
    setDesiable(menusEnum) {
      for (const menuInfo of menusEnum) {
        menuInfo.disabled = true
        if(menuInfo.children && menuInfo.children.length > 0) {
          this.setDesiable(menuInfo.children)
        }
      }
      return menusEnum;
    },
    deleteInfo(scope) {
      console.log(scope.row)
      this.$confirm('确定删除该职务?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    add(row) {
      this.reset()
      this.dialogTitle = '添加职务'
      getMenuTreeList().then(menusRes => {
        this.menusEnum = menusRes.data
        getListByJobDutyId(0).then(menuListRes=>{
          console.log("menuListRes:", menuListRes.data)
          this.$refs.menusForm.setCheckedKeys(menuListRes.data.filter(id=> !this.menusEnum.map(menu => menu.id).includes(id)))
        })
      })
      this.formVisible = true
    },
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.commitLoading = true
          if(this.form.id) {  // update
            this.form.isManager = Number(this.form.isManager)
            this.$set(this.form, 'menuList', this.$refs.menusForm.getCheckedKeys().concat(this.$refs.menusForm.getHalfCheckedKeys()))
            console.log(this.form)
            edit(this.form).then(res=>{
              console.log(res)
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/dept/jobDuty', name: "JobDuty"});
            }).catch(err=>{
              this.commitLoading = false
              console.log(err)
            })
          } else { // add
            console.log(this.form)
            add(this.form).then(res=>{
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/dept/jobDuty', name: "JobDuty"});
            }).catch(err=>{
              this.commitLoading = false
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    }
  }
}
</script>
